package com.cjjs.jsf.service.impl;

import java.util.Date;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cjjs.jsf.entity.TockenMessage;
import com.cjjs.jsf.entity.WxUser;
import com.cjjs.jsf.repository.TockenMessageRepository;
import com.cjjs.jsf.repository.UserRepository;
import com.cjjs.jsf.service.UserOperaService;

@Service
public class UserOperaServiceImpl implements UserOperaService {
	
	@Autowired
	private UserRepository userRepository;
	
	@Autowired
	private TockenMessageRepository tockenRepository;

	@Override
	public void saveOrUpdateUser(WxUser user) {

		Optional<WxUser> u = this.userRepository.findById(user.getOpenId());
		if(!u.isPresent()) {
			user.setSaveDate(new Date());
			this.userRepository.save(user);
		}else {
			user.setSaveDate(u.get().getSaveDate());
			user.setUpdateDate(new Date());
			this.userRepository.saveAndFlush(user);
		}
	}

	@Override
	public void saveAndUpdateTocken(String tocken) {
		Date startDate = new Date();
		//tocken是2个小时,怕存储时间有差异，因此少加点时间
		Date finishDate = new Date(startDate.getTime()+(7100000));
		
		TockenMessage tm = new TockenMessage();
		tm.setId("access_tocken");
		tm.setCreateDate(startDate);
		tm.setFinishDate(finishDate);
		tm.setValue(tocken);
		
		this.tockenRepository.saveAndFlush(tm);
	}

	@Override
	public String findTocken() {
		
		Optional<TockenMessage> tmo = this.tockenRepository.findById("access_tocken");
		
		if (tmo.isPresent()) {
			TockenMessage tm = tmo.get();
			//如果现在的时间小于完成时间，则tocken是有效的
			if(new Date().getTime()<tm.getFinishDate().getTime()) {
				return tm.getValue();
			}
		}
		
		return null;
	}

}
